package com.cj.sys.entity.security;

import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;

import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;
import javax.persistence.ManyToMany;
import javax.persistence.OrderBy;
import javax.persistence.Table;
import javax.persistence.Transient;

import org.apache.commons.lang.builder.ToStringBuilder;
import org.hibernate.annotations.Cache;
import org.hibernate.annotations.CacheConcurrencyStrategy;
import org.hibernate.annotations.Fetch;
import org.hibernate.annotations.FetchMode;

import com.cj.common.entity.IdEntity;
import com.cj.common.utils.ReflectionUtils;

/**
 * 权限.
 * 
 * @author calvin
 */
@Entity
@Table(name = "AUTHORITIES")
@Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)
public class Authority extends IdEntity {

	private String name;
	private String displayName;
	private Set<User> users = new LinkedHashSet<User>();
	private Set<Resource> resources = new LinkedHashSet<Resource>();
	@Column(nullable=false)
	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	@Column(nullable=false)
	public String getDisplayName() {
		return displayName;
	}

	public void setDisplayName(String displayName) {
		this.displayName = displayName;
	}
	@ManyToMany(mappedBy = "authorities")
	public Set<User> getUsers() {
		return users;
	}

	public void setUsers(Set<User> users) {
		this.users = users;
	}
	//多对多定义
	@ManyToMany
	@JoinTable(joinColumns = { @JoinColumn(name = "AUTHORITIES") }, inverseJoinColumns = { @JoinColumn(name = "RESOURCES") })
	@Fetch(FetchMode.SUBSELECT)
	@OrderBy("id")
	@Cache(usage = CacheConcurrencyStrategy.READ_WRITE)
	public Set<Resource> getResources() {
		return resources;
	}
	// 非持久化属性.
	@Transient
	public String getResourceNames() throws Exception {
		return ReflectionUtils.fetchElementPropertyToString(resources, "name", ", ");
	}

	// 非持久化属性.
	@Transient
	@SuppressWarnings("unchecked")
	public List<Long> getResourceIds() throws Exception {
		return ReflectionUtils.fetchElementPropertyToList(resources, "id");
	}
	public void setResources(Set<Resource> resources) {
		this.resources = resources;
	}

	@Override
	public String toString() {
		return ToStringBuilder.reflectionToString(this);
	}
}
